package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.result.Result;
import com.atguigu.service.AdminService;
import com.atguigu.service.RoleService;
import com.atguigu.util.QiniuUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @PACKAGE_NAME: com.atguigu.controller
 * @CLASSNAME: AdminController
 * @AUTHOR: zhangsan
 * @DATE: 2024/4/17 9:09
 * @SINCE 17.0.7
 * @DESCRIPTION: AdminController 后台管理员 控制层
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    /**
     * 各种页面
     */
    private static final String PAGE_INDEX = "admin/index";
    private static final String PAGE_CREATE = "admin/create";

    private static final String PAGE_EDIT = "admin/edit";
    /**
     * 用户分角色页面
     */
    private static final String PAGE_ASSIGN_SHOW = "admin/assignShow";

    private static final String PAGE_SUCCESS = "common/successPage";

    private static final String LIST_ACTION = "redirect:/admin";

    private static final String PAGE_UPLOAD = "admin/upload";

    /**
     * 七牛云外链
     */
    private static final String shfDomainName = "http://scfvqarb1.hb-bkt.clouddn.com/";
    /**
     * 上传到指定文件夹admin/下
     */
    public static String directory = "admin/";

    @Reference
    private AdminService adminService;

    @Reference
    private RoleService roleService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @RequestMapping
    public String findPage(@NonNull Model model, HttpServletRequest request) {
        Map<String, Object> filters = super.getFilters(request);
        PageInfo<Admin> page = adminService.findPage(filters);
        model.addAttribute("page", page);
        model.addAttribute("filters", filters);
        return PAGE_INDEX;
    }

    /**
     * 跳转到新增管理员页面
     * @return
     */
    @RequestMapping("/create")
    public String toCreate() {
        return PAGE_CREATE;
    }

    @RequestMapping("/save")
    public String saveAdmin(@NonNull Admin admin) {
        String encodePassword = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encodePassword);
        //设置默认头像
        admin.setHeadUrl("http://scfvqarb1.hb-bkt.clouddn.com/admin/d99c4fa6-f85a-4cb5-8aad-4c393d3ad70e");
        Integer i = adminService.insert(admin);
        return PAGE_SUCCESS;
    }

    @RequestMapping("/toEdit/{id}")
    public String toEdit(@PathVariable("id") Long id, @NonNull Model model) {
        log.debug("id = {}",id);
        Admin admin = adminService.getById(id);
        model.addAttribute("admin", admin);
        return PAGE_EDIT;
    }

    @RequestMapping("/update")
    public String updateAdmin(@NonNull Admin admin) {
        log.debug("admin = {}",admin);
        Integer update = adminService.update(admin);
        return PAGE_SUCCESS;
    }

    @RequestMapping("/delete/{id}")
    public String deleteAdmin(@PathVariable("id") Long id) {
        Integer delete = adminService.delete(id);
        return LIST_ACTION;
    }

    @RequestMapping("/uploadShow/{id}")
    public String toUploadPage(@PathVariable("id") Long id,Model model) {
        model.addAttribute("id", id);
        return PAGE_UPLOAD;
    }

    @RequestMapping("/upload/{id}")
    public String upload(@PathVariable("id") Long id,
                         @RequestParam("file") MultipartFile[] files) {
        //发送请求失败,没有收到要上传的文件
        if (files == null || files.length == 0) {
            return null;
        }
        try {
            for (MultipartFile file : files) {
                String fileName = UUID.randomUUID().toString();
                String key = directory+fileName;

                String retKey = QiniuUtil.upload2Qiniu(file.getBytes(), key);
                if (retKey == null || retKey.isEmpty()) {
                    return null;
                }
                //至此说明上传成功,更新数据库中的headUrl
                String headUrl = shfDomainName + key;
                Admin admin = adminService.getById(id);
                admin.setHeadUrl(headUrl);
                Integer update = adminService.update(admin);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return PAGE_SUCCESS;
    }

    /**
     * 查看该用户已有的和没有的权限
     * @param adminId 用户id
     * @return
     */
    @RequestMapping("/assignShow/{adminId}")
    public String assignShow(@PathVariable("adminId") Long adminId, Model model) {
        Map<String, Object> roleMap = roleService.findRoleByAdminId(adminId);
        model.addAttribute("adminId", adminId);
        //model.addAllAttributes(roleMap);默认的key是hashMap
        //model.addAllAttributes(roleMap); = model.addAllAttributes("hashMap",roleMap);
        model.addAttribute(roleMap);
        return PAGE_ASSIGN_SHOW;
    }

    /**
     * 给用户分配角色
     * @param adminId 用户id
     * @param roleIds 给该用户分配的角色
     * @return
     */
    @PostMapping("/assignRole")
    public String assignRole(@RequestParam("adminId") Long adminId,
                             @RequestParam("roleIds") Long[] roleIds) {
        Long[] nonNullRoleIds = Arrays.stream(roleIds).filter(Objects::nonNull).toArray(Long[]::new);
        roleService.assignRolesToAdmin(adminId, nonNullRoleIds);
        return PAGE_SUCCESS;
    }

}
